#include "newactiondialog.h"
#include "ui_newactiondialog.h"

#include <QFileDialog>
#include <QFileInfo>

#include "actionfileparser.h"

NewActionDialog::NewActionDialog(Robot* robot, QWidget *parent) :
    QDialog(parent),
    ui(new Ui::NewActionDialog),
    _robot(robot)
{
    ui->setupUi(this);
    this->setWindowFlags(this->windowFlags() | Qt::WindowStaysOnTopHint);
    connect(ui->browseBtn, SIGNAL(clicked()), this, SLOT(getBaseFile()));
}

NewActionDialog::~NewActionDialog()
{
    delete ui;
}

RobotAction* NewActionDialog::exec(bool createDefault){
    int duration = DEFAULT_DURATION;
    int result;
    RobotAction* newAction;
    QString name = DEFAULT_NAME;
    QString base = "";

    setDuration(duration);
    ui->nameEdit->setFocus();

    //Actually execute the dialog
    result = QDialog::exec();
    if(result == Accepted){
        name = ui->nameEdit->text();
        duration = getDuration();
        base = ui->baseFileName->text();
    }
    else if(!createDefault){
        return NULL;
    }

    //Create the new action
    //TODO: Make sure that the action file parser always returns NULL for invalid files
    newAction = ActionFileParser::parse(base, _robot);
    if(newAction == NULL)
        newAction = new RobotAction(_robot);

    newAction->setName(name);
    newAction->setMotionDuration(duration);
    newAction->setSoundTrackDuration(duration);
    return newAction;
}

void NewActionDialog::getBaseFile(){
    QString filename = QFileDialog::getOpenFileName(this, tr("Select Action File"),
                                                    "", "TiLAR Action Files (*.taf *.txt)");
    QFileInfo fileInfo(filename);
    if(fileInfo.exists()){
        setDuration(ActionFileParser::getDuration(filename));
        ui->baseFileName->setText(filename);
    }
}

int NewActionDialog::getDuration(){
    //Calculate the length based off the two spin box values
    int total = 0;
    int min = ui->minuteSpinBox->value();
    double sec = ui->secondSpinBox->value();

    //convert minutes to milliseconds
    total += min * 60000;
    //convert seconds to milliseconds
    total += (int)(sec * 1000);

    return total;
}

void NewActionDialog::setDuration(int msec){
    //Set the spin boxes
    int remainder, min;
    double sec;

    min = (msec / 60000);
    remainder = msec % 60000;
    sec = MSEC_TO_SECD(remainder);

    ui->minuteSpinBox->setValue(min);
    ui->secondSpinBox->setValue(sec);
}
